/**
 * 消息提示框封装
 * @module Alert
 */
import * as base from '@/common/sju.base.js'

// 默认配置
import { t } from '@/common/sju.i18n.js'

const DEFAULT_CONFIG = {
  INFO_DURATION: 1500,
  CONFIRM_TITLE: t('common.alert.confirm_title'),
  ALERT_TITLE: t('common.alert.alert_title'),
  LOADING_TITLE: t('common.alert.loading_title')
}

/**
 * 显示轻提示消息
 * @param {string} msg 要显示的消息
 * @param {number} [duration=1500] 显示时间(毫秒)
 */
function showInfo(msg, duration = DEFAULT_CONFIG.INFO_DURATION) {
  uni.showToast({
    title: msg,
    icon: 'none',
    duration
  })
}

/**
 * 显示错误提示框
 * @param {string} msg 错误消息
 * @param {string} [title='提示'] 错误标题
 */
function showError(msg, title = t('common.alert.alert_title')) {
  uni.showModal({
    title,
    content: msg,
    showCancel: false
  })
}

/**
 * 显示提示并跳转页面
 * @param {string} msg 提示消息
 * @param {string} url 跳转地址
 * @param {string} [title='提示'] 提示标题
 */
function showAndRedirect(msg, url, title = t('common.alert.alert_title')) {
  uni.showModal({
    title,
    content: msg,
    showCancel: false,
    success: () => uni.redirectTo({ url })
  })
}

/**
 * 显示确认对话框
 * @param {string} msg 消息内容
 * @param {Function} confirm 确认回调
 * @param {Function} [cancel=()=>{}] 取消回调
 * @param {string} [title='请确认'] 对话框标题
 */
function showConfirm(msg, confirm, cancel = () => {}, title = t('alert.confirm_title')) {
  uni.showModal({
    title,
    content: msg,
    success: res => res.confirm ? confirm() : cancel()
  })
}

/**
 * Promise风格的确认对话框
 * @param {string} content 提示内容
 * @param {string} [title='提示'] 对话框标题
 * @returns {Promise<boolean>}
 */
function showConfirmPromise(content, title = t('alert.alert_title')) {
  return new Promise(resolve => {
    uni.showModal({
      title,
      content,
      cancelText: '取消',
      confirmText: '确定',
      success: res => resolve(res.confirm)
    })
  })
}

/**
 * 显示加载中提示
 * @param {string} [title='请等待'] 提示文字
 */
function showLoading(title = t('alert.loading_title')) {
  uni.showLoading({
    title,
    mask: true
  })
}

/**
 * 隐藏加载中提示
 */
function hideLoading() {
  uni.hideLoading()
}

export {
  showInfo,
  showError,
  showAndRedirect,
  showConfirm,
  showConfirmPromise,
  showLoading,
  hideLoading
}
